package com.syezon.wifikey.ad.handler;

import com.blankj.utilcode.util.AppUtils;
import com.hodanet.appadvplatclient.ReportAgent;
import com.hodanet.appadvplatclient.ad.AdInfo;
import com.syezon.wifikey.ad.AdPositionEnum;
import com.syezon.wifikey.ad.receiver.AppInstallReceiver;
import com.syezon.wifikey.ad.receiver.SimpleAppInstallObserver;
import com.syezon.wifikey.channel.ChannelConfig;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

class SelfAppInstallHandler extends SimpleAppInstallObserver {

    private static final String TAG = SelfAppInstallHandler.class.getSimpleName();
    private static SelfAppInstallHandler selfAppInstallHandler;
    private Map<String, AdPositionHolder> PKG_AD_MAP = new ConcurrentHashMap<>();

    private SelfAppInstallHandler() {
        AppInstallReceiver.registerObserver(this);
    }


    public static SelfAppInstallHandler getInstallHandler() {
        if (selfAppInstallHandler == null) {
            synchronized (SelfAppInstallHandler.class) {
                if (selfAppInstallHandler == null) {
                    selfAppInstallHandler = new SelfAppInstallHandler();
                }
            }
        }
        return selfAppInstallHandler;
    }

    /**
     * @param pkgName 移除自有广告信息
     */
    public void removePkgAdInfo(String pkgName) {
        PKG_AD_MAP.remove(pkgName);
    }

    public void notifyInstallStart(String pkgName, AdPositionHolder adPositionHolder) {
        PKG_AD_MAP.put(pkgName, adPositionHolder);
    }

    @Override
    public void added(String pkg) {
        notifyInstallOk(pkg);
    }

    private void notifyInstallOk(String pkgName) {
        try {
            AdPositionHolder adPositionHolder = PKG_AD_MAP.get(pkgName);
            if (adPositionHolder != null && adPositionHolder.getAdInfo() != null) {
                AdInfo adInfo = adPositionHolder.getAdInfo();
                AdPositionEnum adPositionEnum = adPositionHolder.getAdPositionEnum();
                ReportAgent.reportAdvInstall(adInfo, ChannelConfig.getChannel(), AppUtils.getAppVersionCode());
                PKG_AD_MAP.remove(pkgName);
            }
        } catch (Exception e) {
        }
    }
}
